//Taken from http://ayende.com/Blog/archive/2008/07/31/Logging--the-AOP-way.aspx by Ayende

using System;
using System.Text;
using Castle.Core.Interceptor;
using log4net;

namespace WineCellar.Core.Interceptors
{
    public class LoggingInterceptor :IInterceptor
    {
        public void Intercept(IInvocation invocation)
        {
            var logger = LogManager.GetLogger(invocation.TargetType);
            try
            {
                StringBuilder sb = null;
                if (logger.IsDebugEnabled)
                {
                    sb = new StringBuilder(invocation.TargetType.FullName)
                        .Append(".")
                        .Append(invocation.Method)
                        .Append("(");
                    for (int i = 0; i < invocation.Arguments.Length; i++)
                    {
                        if (i > 0)
                            sb.Append(", ");
                        sb.Append(invocation.Arguments[i]);
                    }
                    sb.Append(")");
                    logger.Debug(sb);
                }

                invocation.Proceed();
                if (logger.IsDebugEnabled)
                {

                    logger.Debug("Result of " + sb + " is: " + invocation.ReturnValue);
                }
            }
            catch (Exception e)
            {
                logger.Error(e);
                throw;
            }
        }
    }
}